%           ================ GRIDSTRAIN ================
%           =                                          =  
%           === STRAIN COMPUTATION ON A REGULAR GRID ===
%
% For each node of the regular grid where computation can be carried out, 
% these outputs are provided:
%
%   NODE COORDINATES;
%   MAXIMUM AND MINIMUM STRAIN (OR STRAIN RATE);
%   ERRORS ON STRAIN COMPUTATION (OR STRAIN RATE);
%   ANGLE OF THE MAXIMUM STRAIN DIRECTION WITH RESPECT TO THE NORTH
%       DIRECTION (AZIMUTH);
%   CHANGE IN AREA (OR RATE OF CHANGE IN AREA);
%   NORMALIZED SHEAR (OR RATE OF NORMALIZED SHEAR);
%   GEOMETRIC SIGNIFICANCE OF THE RESULTS;
%   MODELED TRANSLATIONS (OR VELOCITIES);
%   ERRORS ON MODELED TRANSLATIONS (OR VELOCITIES); 
%   RIGID BODY ROTATION AND CORRESPONDING ERROR  
%
% All the data can be saved in MATLAB .mat and/or ASCII .txt files.
%
% PLEASE SEE THE USER'S GUIDE FOR ANY INFORMATION ABOUT THE PROGRAM
% (the program is user-friendly and all the availble options are 
% progressively shown to the user). 

% A. Pesci, G. Teza, 2004, 2005, 2008, 2011, 2018, 2022.

close all; 

%% General and data saving options selection:

figIn = figure('Name','GridStrain');
set(figIn,'Units','normalized','OuterPosition',[0.1 0.1 0.7 0.5]);
imshow([])
title('GridStrain initial option','FontSize',24,'Color','b');  
axis equal;
lsgen = {...
    'NEW CALCULATIONS OF BOTH GRID AND STRAIN FIELD',...
    'GRID ALREADY AVAILABLE, CALCULATION OF STRAIN FIELD',...
    'LOADING OF AVAILABLE GRID AND STRAIN DATA',...
    'EXIT FROM GRIDSTRAIN'};
lbIn = uicontrol(figIn,'Style','listbox',...
        'string',lsgen,...
        'FontSize',14,...
        'Units','normalized','Position', [0.2 0.3 0.60 0.40],...
        'Callback', 'uiresume(gcbf)');
    uiwait(figIn);
    optGen = lbIn.Value;
    delete(lbIn);
    close(figIn);
    
if optGen ~= 4
    
    figSave = figure('Name','GridStrain');
    set(figSave,'Units','normalized','OuterPosition',[0.1 0.1 0.7 0.5]);
    imshow([]);
    title('GridStrain data saving options','FontSize',24,'Color','g');  
    axis equal;
    lSave = {'AUTOMATIC DATA SAVING WITH A DEFINED NAME',...
        'MANUAL DATA SAVING',...
        'NO DATA SAVING'};
    lbSave = uicontrol(figSave,'Style','listbox',...
        'String',lSave,...
        'FontSize',14,...
        'Units','normalized','Position', [0.2 0.3 0.60 0.40],...
        'Callback', 'uiresume(gcbf)');
    uiwait(figSave);
    menufina = lbSave.Value;
    delete(lbSave);
    close(figSave);

    if menufina == 1
        prompty = {'FILENAME COMMON PART'};
        acquis = inputdlg(prompty,'FILENAME COMMON PART',1);
        if ~isempty(acquis)
            filecom = acquis{:};
        else
            filecom = [];
        end
        optSave = true;
    elseif menufina == 2
        filecom = []; 
        optSave = true;
    else
        filecom = []; 
        optSave = false;
    end
    
else
    
    return
    
end
if ~isempty(filecom)
    filecom = [filecom '2D']; 
end


%% Data load, grid generaton and/or modification

if optGen == 1     % in this case, the grid is unavailable
    
    GSS = gs_dataload;
    if isempty(GSS.East)
        fprintf('\nNo valid input data - exit from GridStrain \n'); 
        return
    end
    
else
   
    [filen, pathn] = uigetfile({'*.mat','MATLAB (*.mat) files'},...
        'INPUT MATLAB FILE');
    if isequal(filen,0) || isequal(pathn,0)
        filena = [];    % cancel was pressed by user
        fprintf('\nNo a data file was selected \n');
        return
    else
        filena = fullfile(pathn,filen);
    end
    GSSLoad = load(filena);
    try
        GSS = GSSLoad.GSS;
        if isempty(GSS.XGridStep)
            Iok = false;
        else
            Iok = true;
        end
    catch
        Iok = false;
    end
    if ~Iok
        fprintf('\nInvalid input data \n');
        return
    end
    
end

if ismember(optGen,[1 2]) 
    
    figRem = figure('Name','GridStrain');
    set(figRem,'Units','normalized','OuterPosition',[0.1 0.1 0.7 0.5]);
    imshow([]);
    title('Optional point exclusion','FontSize',24,'Color','g');  
    axis equal;
    lRem = {...
        'EXCLUSION OF ONE OR MORE POINTS FROM CALCULATIONS',...
        'NO POINT EXCLUSION'};
    lbRem = uicontrol(figRem,...
        'Style','listbox',...
        'String',lRem,...
        'FontSize',14,...
        'Units','normalized',...
        'Position',[0.2 0.3 0.60 0.40],...
        'Callback', 'uiresume(gcbf)');
    uiwait(figRem);
    menuno = lbRem.Value;
    delete(lbRem);
    close(figRem);

    if menuno == 1
        GSS = gs_nopoints(GSS);
    elseif optGen == 1
        GSS.IncludedPoints = true(size(GSS.East)); 
    end
    
    if optGen == 2
        npe = GSS.IncludedPoints;
        if sum(npe) < numel(npe)
            figRem = figure('Name','GridStrain');
            set(figRem,'Units','normalized','OuterPosition',[0.1 0.1 0.7 0.5]);
            imshow([]);
            title('Optional point reintroduction','FontSize',24,'Color','g');  
            axis equal;
            lRem = {...
                'REINTRODUCTION OF POINTS EXCLUDED IN PREVIOUS SESSIONS',...
                'NO POINT REINTRODUCTION'};
            lbRem = uicontrol(figRem,'Style','listbox',...
                'String',lRem,...
                'FontSize',14,...
                'Units','normalized','Position',[0.2 0.3 0.60 0.40],...
                'Callback', 'uiresume(gcbf)');
            uiwait(figRem);
            menuye = lbRem.Value;
            delete(lbRem);
            close(figRem);

            if menuye == 1
                GSS = gs_yepoints(GSS);
            end
        end
    end
            
    if optGen == 1
        GSS = gs_gridgene(GSS);
        try
            GSS.XGridStep;
        catch
            return
        end
    else
        GSS = gs_gridmod(GSS);
    end
    
    if optSave
        if ~isempty(filecom)
            save([filecom 'G.mat'],'GSS');
        else
            filenig = savecond('','.mat','GRID DATA SAVING');
            if ~isempty(filenig)
                save(filenig,'GSS');
            end
        end
    end
    
end

%% Strain computation and/or visualization

nocont = 0; 
nnn = 1;
while nocont == 0
    
    if nnn == 1
        if ismember(optGen,[1 2])
            % in this case the strain field should be computed. These lines
            % will be used below
            dx = GSS.XGridStep;
            dy = GSS.YGridStep;
            d0 = 3*min(dx,dy);
        else   
            % in this case the strain data should be already available
            % (a MATLAB file was already managed, see section dataload above) 
            EMAX = GSS.MaxStrainMatrix;
            if isempty(EMAX)
                fprintf('\nInvalid input data: unavailable strain field \n');
                return
            end 
            disp('Visualization in progress...');
            %--------------------------------------------------------------
            gs_strashow(GSS);
            %--------------------------------------------------------------
            disp('... Visualization completed');
            % Grid report:
            fprintf('\n----------------------------------------------');
            grep = gs_gridReport(GSS);
            d0 = GSS.ScaleFactor;
            fprintf('%s \n\nScale factor: %f m \n',grep,d0);
            fprintf('----------------------------------------------\n');
        end
    end
    
    if (optGen == 1)||(optGen == 2)||((optGen == 3)&&(nnn > 1))   % <- note the condition
        % Scale factor management:  
        prompty = {'Scale factor'};
        defansy = {num2str(d0)};
        fields  = {'d0'};
        acquis  = inputdlg(prompty,'SCALE FACTOR MANAGEMENT',1,defansy);
        if ~isempty(acquis)
            acq = cell2struct(acquis,fields); 
            d0m = str2double(acq.d0);
        else
            d0m = [];
        end
        if ~isempty(d0m)    % in the "cancel case" gs_itera is not executed
            
            d0 = d0m;
            % Iterations on all grid nodes:   
            GSS = gs_itera(GSS,d0);
            % Strain field visualizazion:
            gs_strashow(GSS);
            % Report visualization:
            fprintf('\n----------------------------------------------\n');
            grep = gs_gridReport(GSS);
            fprintf('%s \n\nScale factor: %f m\n',grep,d0);
            fprintf('----------------------------------------------\n');
    
            if optSave
                if ~isempty(filecom)
                    save([filecom 'SF' num2str(round(d0)) '.mat'],'GSS');
                else
                    filenis = savecond('','.mat','STRAIN FIELD DATA SAVING');
                    if ~isempty(filenis)
                        save(filenis,'GSS');
                    end
                end
            end
            
        end
    end
    
    figFin = figure('Name','GridStrain');
    set(figFin,'Units','normalized','OuterPosition',[0.1 0.1 0.7 0.5]);
    imshow([]);
    title('Scale factor choice','FontSize',24,'Color','g');  
    axis equal;
    lFin = {'ANOTHER SCALE FACTOR','EXIT'};
    lbFin = uicontrol(figFin,...
        'Style','listbox',...
        'String',lFin,...
        'FontSize',14,...
        'Units','normalized',...
        'Position',[0.2 0.3 0.60 0.40],...
        'Callback','uiresume(gcbf)');
    uiwait(figFin);
    optFin = lbFin.Value;
    delete(lbFin);
    close(figFin);
    
    if optFin == 2
        nocont = 1; 
        fprintf('\n === GOOD BYE === \n'); 
    end  
    nnn = nnn+1;
    
end